﻿using System;
using System.Collections.Generic;
using System.Web;
using System.IO;
using System.Text;
using System.Security.Cryptography;
using System.Reflection;
using System.ComponentModel;

namespace H2.NET
{
    public class FileHandler : IHttpHandler
    {
        private string fileName;
        private string filePath;

        #region 方法 ProcessRequest(请求处理)
        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        public void ProcessRequest(HttpContext context)
        {
            fileName = Util.Decrypt(HttpUtility.UrlDecode(context.Request.Params["File"]));
            filePath = System.Configuration.ConfigurationManager.AppSettings["Path"] + @"\" + fileName;

            FileStream fs = null;
            try
            {
                fs = File.OpenRead(filePath);

                context.Response.Clear();
                long count = 102400;
                byte[] buffer = new byte[count];
                long fs_lenght = fs.Length;

                context.Response.ContentType = "application/octet-stream";
                context.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName.Split('~')[1],System.Text.Encoding.UTF8));
                while (fs_lenght > 0 && context.Response.IsClientConnected)
                {
                    long read_lenght = fs.Read(buffer, 0, (int)(count > fs_lenght ? fs_lenght : count));
                    context.Response.OutputStream.Write(buffer, 0, (int)read_lenght);
                    context.Response.Flush();

                    fs_lenght = fs_lenght - read_lenght;
                }
            }
            catch (Exception)
            {

            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();
                    context.Response.End();
                }
                else
                {
                    context.Response.Write("<script language='javascript'>alert('File does not exist!');</script>");
                }

                context.Response.Write("<script language='javascript'>window.close();</script>");
            }
        }

        public bool IsReusable
        {
            get { return true; }
        }
        #endregion
    }        
}